package question10;

/**
 * @FileName Test
 * @Description
 * @Author Sword
 * @date 2024-12-04
 **/
public class Test {
    public static void main(String[] args) {
        //编程实现二分查找法，查找某个单词是否在给定的字典里。
        String[] dictionary = {"apple", "banana", "cherry", "date", "fig", "grape", "kiwi", "lemon", "mango", "orange"};

        // 要查找的单词
        String wordToFind = "kiwi";

        // 执行二分查找
        boolean found = myBinarySearch(dictionary, wordToFind);

        // 输出结果
        if (found) {
            System.out.println(wordToFind + " is in the dictionary.");
        } else {
            System.out.println(wordToFind + " is not in the dictionary.");
        }
    }

    private static boolean myBinarySearch(String[] dictionary, String wordToFind) {
        int left = 0;
        int right = dictionary.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;

            // 比较中间元素与目标值
            if (dictionary[mid].equals(wordToFind)) {
                return true; // 找到目标值
            } else if (dictionary[mid].compareTo(wordToFind) < 0) {
                left = mid + 1; // 目标值在右侧
            } else {
                right = mid - 1; // 目标值在左侧
            }
        }

        return false;
    }
}
